package com.zonhar.autofeed.cron;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pi4j.io.gpio.RaspiPin;
import com.zonhar.autofeed.common.device.dht.Data;
import com.zonhar.autofeed.common.device.dht.Dht11Device;
import com.zonhar.autofeed.entities.entity.SensorEntity;
import com.zonhar.autofeed.service.SensorLogService;
import com.zonhar.autofeed.service.SensorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * hx温度湿度自动采集
 */
@Component
public class HxCron {

    private final static Logger log = LoggerFactory.getLogger(HxCron.class);


    @Autowired
    private SensorLogService sensorLogService;

    @Autowired
    private SensorService sensorService;

    /**
     * 自动数据采集
     */
    @Scheduled(cron="0 0 1/2 * * ?")
    public void run(){
        this.asyncHx();
    }

    @Async
    public void asyncHx(){
        if(getSenor(2L)){
            Data datas = Dht11Device.getDht11Data(RaspiPin.GPIO_07);
            sensorLogService.saveLog(JSONObject.parseObject(JSON.toJSONString(datas)),"温湿传感器");
        }else {
            log.info("HX11传感器已停用");
        }
    }

    private boolean getSenor(Long id){
        QueryWrapper<SensorEntity> sensorEntityQueryWrapper =new QueryWrapper<>();
        sensorEntityQueryWrapper.eq("id",id);
        SensorEntity sensorEntity = sensorService.getOne(sensorEntityQueryWrapper);
        return sensorEntity.getStat().equals(0);
    }

}
